<?php

/**
 * Class CartController
 * 购物车控制器(实现购物车增加、修改、查看、删除业务)
 *
 */
class CartController extends \BaseController
{
    public function __construct()
    {
        CookieCart::start();
    }

    /**
     * 获取购物车商品列表
     * 返回json格式:
     *```
     * [
     *   {
     *     "id":
     *     "name":
     *     "image":
     *     "price":
     *     "count":
     *     "amount":
     *   }
     * ]
     *```
     * @return Response
     */
    public function index()
    {
        $cookieCart = CookieCart::getProducts();
        try {
            return Response::json(Cart::getProducts($cookieCart));
        } catch (Exception $e){
            parent::failResponse('内部服务错误.');
        }
    }



    /**
     *　新增商品至购物车
     * 请求json格式:
     * ```
     * {
     *   "id":
     *   "count":
     * }
     * ```
     * 返回json格式:
     * ```
     * {
     *   "status":
     *   "message":
     * }
     * ```
     * @return Response
     */
    public function store()
    {
        $product = Input::all();
        $id = $product['id'];
        $amount = Product::find($id)['amount'];
        $parameters = ['count' => $product['count'], 'amount' => $amount];
        try {
            $cookie = CookieCart::refreshProduct($id, $parameters);
        } catch (Exception $e) {
            parent::failResponse('内部服务错误.');
        }
        return parent::successResponse()->withCookie($cookie);
    }



    /**
     *　修改购物车中某一商品信息
     * 请求json格式:
     * ```
     * {
     *   "count":
     * }
     * ```
     * store
     * @param  int  $id
     * @return Response
     */
    public function update($id)
    {
        try {
            $cookie = CookieCart::refreshProduct($id, Input::all());
        } catch (Exception $e) {
            parent::failResponse('内部服务错误.');
        }
        return parent::successResponse()->withCookie($cookie);
    }


    /**
     * Remove the specified resource from storage.
     *　删除购物车中某一商品
     * 返回json格式:
     * ```
     * {
     *   "status":
     *   "message":
     * }
     * ```
     * @param  int  $id
     * @return Response
     */
    public function destroy($id)
    {
        try {
            $cookie = cookieCart::deleteProduct($id);
        } catch (Exception $e) {
            parent::failResponse('内部服务错误');
        }
        return parent::successResponse()->withCookie($cookie);
    }

}
